package com.yunshang.ysmall.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.ChannelException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.exception.RateLimitException;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.PingppObject;
import com.pingplusplus.model.Webhooks;
import com.yunshang.ysmall.model.MbAddrInfo;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.model.OrderItemInfo;
import com.yunshang.ysmall.model.ProductImgList;
import com.yunshang.ysmall.model.ProductInfo;
import com.yunshang.ysmall.model.ProductTypeInfo;
import com.yunshang.ysmall.service.MemberService;
import com.yunshang.ysmall.service.ProductService;
import com.yunshang.ysmall.util.Constants;
import com.yunshang.ysmall.util.DateUtils;
import com.yunshang.ysmall.util.HttpClientUtils;
import com.yunshang.ysmall.util.MD5Utils;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("/order")
public class OrderController {

	private static Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Resource
	ProductService productService;
	@Resource
	MemberService memberService;

	public static final String ROOT = "static/upload-dir/";

	@RequestMapping("/toorderlist/{action}")
	public String toorderlist(@PathVariable("action") String action, OrderInfo orderInfo, Model model) {
		Map params = new HashMap();
		if (orderInfo.getOrderId() != null && !"".equals(orderInfo.getOrderId())) {
			params.put("orderId", orderInfo.getOrderId());
		}
		if (orderInfo.getMemberId() != null && !"".equals(orderInfo.getMemberId())) {
			params.put("memberId", orderInfo.getMemberId());
		}
		if ("waithandle".equals(action)) {
			params.put("orderStatus", 2);
			params.put("transferStatus", 0);
		}
		params.put("startIndex", 0);
		params.put("pageSize", 10000);
		model.addAttribute("orderList", memberService.getOrderListByParams(params));
		return "/mng/main/order/orderlist";
	}

	@RequestMapping("/detail")
	public String edit(String oid, Model model) {
		OrderInfo orderInfo = memberService.getOrderInfoById(oid);
		orderInfo.setOrderTs(
				DateUtils.string2Date(orderInfo.getOrderDate() + orderInfo.getOrderTime(), "yyyyMMddHHmmss"));
		List<OrderItemInfo> itemList = memberService.getOrderItemListByOrderId(oid);
		model.addAttribute("itemList", itemList);
		model.addAttribute("orderInfo", orderInfo);
		MbAddrInfo addressInfo = memberService.getAddrById(orderInfo.getAddrId());
		model.addAttribute("addressInfo", addressInfo);
		return "/mng/main/order/detail";
	}

	@RequestMapping("/fahuo")
	public String editpro(OrderInfo orderInfo, Model model) {
		memberService.updateOrder(orderInfo);
		return "redirect:/order/toorderlist/all";
	}

	@RequestMapping("/notify")
	public void notify(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF8");
			// 获取头部所有信息
			Enumeration headerNames = request.getHeaderNames();
			while (headerNames.hasMoreElements()) {
				String key = (String) headerNames.nextElement();
				String value = request.getHeader(key);
				System.out.println(key + " " + value);
			}
			// 获得 http body 内容
			BufferedReader reader = request.getReader();
			StringBuffer buffer = new StringBuffer();
			String string;
			while ((string = reader.readLine()) != null) {
				buffer.append(string);
			}

			reader.close();

			// 解析异步通知数据
			Event event = Webhooks.eventParse(buffer.toString());
			if ("charge.succeeded".equals(event.getType())) {
				response.setStatus(200);
				Object obj = Webhooks.getObject(buffer.toString());
				Charge charge = (Charge) obj;   
				OrderInfo orderInfo =memberService.getOrderInfoById(charge.getOrderNo());
				//去扣积分
				if(memberpay(orderInfo)){
					orderInfo.setOrderStatus(2);
				}else{
					orderInfo.setOrderStatus(5);
				}
				memberService.updateOrder(orderInfo);
			} else if ("refund.succeeded".equals(event.getType())) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private boolean memberpay(OrderInfo orderInfo){
		try{
			String url = "http://211.219.83.86:8090/scapi.aspx?client_id=YUNSHANG";
			String key = "123456";
			String param = URLEncoder.encode("{\"USER_ALIAS\":\""+orderInfo.getMemberId()+"\",\"PAY_TYPE\":\"3\",\"MONEY\":\""+orderInfo.getTransBonus()+"\",\"ORDER_NO\":\""+orderInfo.getOrderId()+"\",\"PAY_IP\":\"127.0.0.1\"}","utf-8");
			String ndate = DateUtils.currentDate("HHmmss");
			String md5 = MD5Utils.MD5("YUNSHANG"+key+ndate).toLowerCase();
			String requestUrl = url+"&schema_name=GET_USER_ACCOUNT_PAY&parameter="+param+"&ndate="+ndate+"&md5="+md5;
			logger.info("requestUrl:"+requestUrl);
			String result = HttpClientUtils.httpGet(requestUrl);
			logger.info("result:"+result);
		// {"result":"success","total":1,"data":[{"NAME":"乔江2","DWALLET":"0.74","USER_ALIAS":"AN809702","PASSWORD":"96e79218965eb72c92a549dd5a330112","ISLOGIN":1.0}]};
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				if ("1".equals(data.getString("ISPAY").split("|")[0])) {
					return true;
				}
			}
			return false;
		}catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
	}

}
